package com.hl.manage.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hl.manage.entity.Group;
import com.hl.manage.entity.Menu;
import com.hl.manage.service.IGroupService;
import com.hl.manage.service.IMenuService;
import com.hl.manage.utils.SendResult;

public class LogCostInterceptor implements HandlerInterceptor {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	public IMenuService iMenuService;

    public IGroupService iGroupService;

    public LogCostInterceptor(IMenuService iMenuService,
    		IGroupService iGroupService){
        this.iMenuService = iMenuService;
        this.iGroupService = iGroupService;
    }
	
    long start = System.currentTimeMillis();
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
    	start = System.currentTimeMillis();
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("account")==null) {
        	 returnJson(httpServletResponse,httpServletRequest,400002,"登录已过期",null);
             return false;
		}
        //判断登录用户是否有此控制器权限
        String groupIdString = session.getAttribute("loginGroup").toString();
        Group group =  iGroupService.getById(groupIdString);
        if(!group.getMenuIdlist().toString().equals("-1")) {
        	String [] meString = group.getMenuIdlist().toString().split(",");
        	
        	QueryWrapper<Menu> qWrapper = Wrappers.query();
        	qWrapper.eq("route", httpServletRequest.getServletPath());
        	Menu menu = iMenuService.getOne(qWrapper);
        	if (menu==null) {
        		returnJson(httpServletResponse,httpServletRequest,400001,"请求失败，用户权限不足",null);
                return false;
			}else {
				Integer meInteger = menu.getId();
				if(!Arrays.asList(meString).contains(meInteger.toString())) {
					returnJson(httpServletResponse,httpServletRequest,400001,"请求失败，用户权限不足",null);
	                return false;
				}
			}
        }
        return true;
    }
 
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }
 
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
    private void returnJson(HttpServletResponse response,HttpServletRequest request,Integer code,String msg,String data){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            SendResult sResult = new SendResult();
			sResult.setCode(code);
			sResult.setMsg(msg);
			sResult.setData(data);
            writer.print(sResult);
        } catch (IOException e){
            logger.error("拦截器输出流异常"+e); 
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}
